/*

                  写字楼里写字间，写字间里程序员；
                  程序人'猿'写程序，又拿程序换酒钱。
                  酒醒只在网上坐，酒醉还来网下眠；
                  酒醉酒醒日复日，网上网下年复年。
                  但愿老死电脑间，不愿鞠躬老板前；
                  奔驰宝马贵者趣，公交自行程序员。
                  别人笑我忒疯癫，我笑自己命太贱；
                  不见满街漂亮妹，哪个归得程序'猿'？
━━━━━━神兽出没━━━━━━
 ┏┓   ┏┓
┏┛┻━━━┛┻┓
┃       ┃
┃   ━   ┃
┃ ┳┛ ┗┳ ┃
┃       ┃
┃   ┻   ┃
┃       ┃
┗━┓   ┏━┛
  ┃   ┃                    神兽保佑, 永无BUG!
  ┃   ┃       Code is far away from bug with the animal protecting
  ┃   ┗━━━┓
  ┃       ┣┓
  ┃       ┏┛
  ┗┓┓┏━┳┓┏┛
   ┃┫┫ ┃┫┫
   ┗┻┛ ┗┻┛
 */

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;

/**
 * Created by 石头哥哥 on 5/12/16.
 * <p>
 * common
 * <p>
 * com.cl.mongo
 * <p>
 * comments:  存储文件测试
 * <p>
 * <p>
 * MongoDB GridFS相关
 * http://blog.csdn.net/zhu_tianwei/article/details/44278095
 */
public class MongoGridFSTest {

    private static MongoClient mongoClient = null;
    private static GridFS gridFS = null;
    private static String bucket = "gridfs";

    public static void main(String[] args) throws UnknownHostException, Exception {
        mongoClient = new MongoClient("127.0.0.1", 27017);
        gridFS = new GridFS(new DB(mongoClient, bucket));

        String file = "pic/ub.png";
        String path = ClassLoader.getSystemResource(file).getPath();

        String fileName = "ub.png";
        //把文件保存到gridfs中，并以文件的md5值为id
        save(new FileInputStream(path), fileName, fileName);
        //据文件名从gridfs中读取到文件

        GridFSDBFile gridFSDBFile = getByFileName(fileName);
        if (gridFSDBFile != null) {
            System.out.println("filename:" + gridFSDBFile.getFilename());
            System.out.println("md5:" + gridFSDBFile.getMD5());
            System.out.println("length:" + gridFSDBFile.getLength());
            System.out.println("uploadDate:" + gridFSDBFile.getUploadDate());
            System.out.println("--------------------------------------");
            File _file = new File(path.replaceAll(file, "") + "pic/ub1.png");
            gridFSDBFile.writeTo(_file);
        } else {
            System.out.println("can not get file by name:" + fileName);
        }

        mongoClient.close();
    }


    /**
     *  测试保存图片
     *
     * @param in
     * @param id
     * @param fileName
     * @throws IOException
     */
    public static void save(InputStream in, Object id, String fileName) throws IOException {
        DBObject query = new BasicDBObject("_id", id);
        GridFSDBFile gridFSDBFile = gridFS.findOne(query);
        if (gridFSDBFile == null) {
            GridFSInputFile gridFSInputFile = gridFS.createFile(in);
            /**
             * 设置保存图片信息熟悉
             */
            gridFSInputFile.setId(id);
            gridFSInputFile.setFilename(fileName);
            gridFSInputFile.setChunkSize(in.available());
            gridFSInputFile.setContentType("png");
//            gridFSInputFile.setMetaData("png");
            gridFSInputFile.save();
        }
    }

    /**
     * 据id返回文件
     *
     * @param id
     * @return
     */
    public static GridFSDBFile getById(Object id) {
        DBObject query = new BasicDBObject("_id", id);
        return gridFS.findOne(query);
    }

    /**
     * 据文件名返回文件，只返回第一个
     *
     * @param fileName
     * @return
     */
    public static GridFSDBFile getByFileName(String fileName) {
        DBObject query = new BasicDBObject("filename", fileName);
        return gridFS.findOne(query);
    }
}
